package com.itheima.controller.login;

import com.itheima.controller.BaseServlet;
import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.domain.UserInfo;
import com.itheima.utils.BeanUtil;
import com.itheima.utils.MD5Util;
import com.itheima.utils.ServletUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 用户 控制层
 */
@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {

    /**
     * 登录功能
     * @param req
     * @param resp
     */
    private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取输入的账号密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //获取保存密码到cookie标记
        String saveFlag = req.getParameter("ck");
        //密码MD5加密
        password = MD5Util.md5(password);
        //通过email和密码找到用户
        UserInfo user = loginService.login(username, password);
        //判断是否有返回
        if(user != null){
            //获取到角色权限列表
            List<String> permissions = userService.findPerById(user.getId());
            //封装进user
            List<Permission> userPermissions = new ArrayList<Permission>();
            for (int i = 0; i < permissions.size(); i++) {
                Permission p = new Permission();
                p.setUrl(permissions.get(i));
                userPermissions.add(p);
            }
            Role role = new Role();
            role.setPermissions(userPermissions);
            user.setRole(role);
            //登录成功 把用户对象设置到作用域 并跳转
            req.setAttribute("user",user);
            //登录成功 把用户存到会话域 验证登录使用
            req.getSession().setAttribute("user",user);
            req.getSession().setMaxInactiveInterval(3600);
            //判断是否需要保存到cookie
            if(saveFlag != null){
                if(saveFlag.equals("1")){
                    //创建cookie 存入数据 默认是半小时
                    Cookie usernameCookie = new Cookie("username", username);
                    Cookie passwordCookie = new Cookie("password", password);
                    //设置有效期 一小时
                    usernameCookie.setMaxAge(3600);
                    passwordCookie.setMaxAge(3600);
                    // 可在同一应用服务器内共享方法
                    usernameCookie.setPath("/");
                    passwordCookie.setPath("/");
                    //添加cookie
                    resp.addCookie(usernameCookie);
                    resp.addCookie(passwordCookie);
                }
            }
            //跳转main
            req.getRequestDispatcher("/pages/common/main.jsp").forward(req,resp);
        }else {
            //登录失败 跳转到登录 并弹窗登陆失败
            req.getSession().setAttribute("isNotLogin","1");
            req.getRequestDispatcher("/pages/login.jsp").forward(req,resp);
        }
    }

    /**
     * 登出
     * @param req
     * @param resp
     */
    private void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //删除cookie
        //创建cookie 存入数据 默认是半小时
        Cookie usernameCookie = new Cookie("username", null);
        Cookie passwordCookie = new Cookie("password", null);
        //设置有效期 0
        usernameCookie.setMaxAge(0);
        passwordCookie.setMaxAge(0);
        // 可在同一应用服务器内共享方法
        usernameCookie.setPath("/");
        passwordCookie.setPath("/");
        //添加cookie
        resp.addCookie(usernameCookie);
        resp.addCookie(passwordCookie);

        //删除会话域中的用户对象
        req.getSession().setAttribute("user",null);
        //跳转登录页面
        req.getRequestDispatcher("/pages/login.jsp").forward(req,resp);

    }


    /**
     * 修改密码
     * @param req
     * @param resp
     */
    private void changePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        UserInfo user = (UserInfo)req.getSession().getAttribute("user");
        //获取两个密码
        String newPwd = req.getParameter("newPwd");
        String newPwd2 = req.getParameter("newPwd2");

        //设置成功失败标记
        String flag = "false";
        if(newPwd.equals(newPwd2)){
            //转md5
            newPwd = MD5Util.md5(newPwd);
            //设置新密码
            loginService.updatePwd(user.getId(),newPwd);
            //设置成功标记
            flag = "true";
        }

        //设置成功失败标记
        req.getSession().setAttribute("updateFlag",flag);
        //跳转登录页面
        req.getRequestDispatcher("/pages/common/changeInfo.jsp").forward(req,resp);

    }

    /**
     * 刷新
     * @param req
     * @param resp
     */
    private void flush(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //清除请求域的登陆失败值
        req.getSession().setAttribute("isNotLogin","0");
        //转发
        req.getRequestDispatcher("/pages/login.jsp").forward(req,resp);
    }

    /**
     * 修改头像
     * @param req
     * @param resp
     */
    private void changProfile(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //判断是否支持文件上传操作
        if(ServletFileUpload.isMultipartContent(req)){
            //创建磁盘文件工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //创建Servlet核心文件上传对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //从request读取数据
            List<FileItem> fileItems = fileUpload.parseRequest(req);
            //获取图片名称
            String picture = req.getParameter("picture");

            for (FileItem fileItem : fileItems) {
                //判断非表单数据
                if(!fileItem.isFormField()){
                    //判断非空
                    if(StringUtils.isNotBlank(fileItem.getName())){
                        System.out.println(fileItem.getName());
                        fileItem.write(new File(this.getServletContext().getRealPath("profile"),picture));
                    }
                }
            }
            //设置成功失败标记
            req.getSession().setAttribute("profileFlag","true");
            //更改完头像 跳转
            req.getRequestDispatcher("/pages/common/changeProfile.jsp").forward(req,resp);
        }
    }
}
